package com.eastseeway.radioproject.radio;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.eastseeway.radioproject.R;
import com.eastseeway.radioproject.base.BaseActivity;
import com.eastseeway.radioproject.base.Const;
import com.eastseeway.radioproject.databinding.ActivityHandleRadioBinding;
import com.eastseeway.radioproject.databinding.ItemShortcutInfoBinding;
import com.eastseeway.radioproject.engineer.EngineerActivity;
import com.eastseeway.radioproject.entities.Bean1FromHandle;
import com.eastseeway.radioproject.entities.BeanFromBottomBoard;
import com.eastseeway.radioproject.entities.BeanFromEnergyBoard;
import com.eastseeway.radioproject.entities.BeanFromNegativePressureBoard;
import com.eastseeway.radioproject.entities.MessageEvent;
import com.eastseeway.radioproject.entities.OperationParams;
import com.eastseeway.radioproject.main.DeviceStatus;
import com.eastseeway.radioproject.test.TestActivity;
import com.eastseeway.radioproject.utils.AnimUtils;
import com.eastseeway.radioproject.utils.ByteUtil;
import com.eastseeway.radioproject.utils.CommandGenerator;
import com.eastseeway.radioproject.utils.SPHelper;
import com.king.view.arcseekbar.ArcSeekBar;
import com.eastseeway.radioproject.views.wheel.WheelPicker;
import com.google.gson.Gson;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import struct.StructException;

/**
 * 有负压的手柄
 */
public class HandleRadioActivity extends BaseActivity<ActivityHandleRadioBinding,HandleRadioViewModel> {
    private boolean isAccept = true,isElectrodeDetected = false;
    private ShortcutInfoAdapter mShortcutInfoAdapter;
    private final List<Integer> mShortcutList = Arrays.asList(R.mipmap.icon_radio_pre_1,R.mipmap.icon_radio_pre_2,R.mipmap.icon_radio_pre_3,R.mipmap.icon_radio_pre_4,R.mipmap.icon_radio_pre_5);
    private final List<Integer> mShortcutLList = Arrays.asList(R.mipmap.icon_radio_pre_l1,R.mipmap.icon_radio_pre_l2,R.mipmap.icon_radio_pre_l3,R.mipmap.icon_radio_pre_l4,R.mipmap.icon_radio_pre_l5);
    private boolean isPreviousBit6HasException = false,isPreviousBit7HasException = false;
    private boolean isInitialized = false;
    private boolean isBit6HasException,isHandleWorking = false;
    private boolean readyToPlaySound7  = false;
    private boolean waitEnergyBoardReply = false;
    private int energyOffset = 5;
    private final int idhpOffset = 10;
    private final int idlpOffset = 30;
    private final int idpOffset = 1;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_handle_radio;
    }

    @Override
    protected Class<HandleRadioViewModel> getVMClass() {
        return HandleRadioViewModel.class;
    }

    @Override
    protected void initEvent() {
        mBinding.handleRadioShortcut.setLayoutManager(new GridLayoutManager(this,5));
        mShortcutInfoAdapter = new ShortcutInfoAdapter();
        mBinding.handleRadioShortcut.setAdapter(mShortcutInfoAdapter);

//        待机 准备 工作按钮
        mBinding.handleRadioStart.setOnClickListener(v->{
            playClickSound();
            if (!isElectrodeDetected) {
                return;
            }
            if (isBit6HasException) {
                return;
            }
            if (Boolean.TRUE.equals(mViewModel.getIsPreMode().getValue())) {
                mViewModel.getIsPreMode().setValue(false);
            }
            mBinding.handleRadioWheelContinuousDischargePeriod.stopScroll();
            mBinding.handleRadioWheelPressure.stopScroll();
            mBinding.handleRadioWheelRightDepth.stopScroll();
            new Handler(Looper.getMainLooper()).postDelayed(()->{
                mViewModel.changeWorkState();
            },50);
        });

//      版本号和返回按钮
//        mBinding.textView.setText(BuildConfig.VERSION_NAME);
        mBinding.logo.setOnClickListener(v->{
            startActivity(new Intent(this, TestActivity.class));

//            playGif(false);
//            mViewModel.checkElectrode("S003");
//            mViewModel.sendHandleCommand();
        });

        mBinding.test.setOnClickListener(v -> {
            continuousClick();
        });

        mBinding.back.setOnClickListener(v->{
            playClickSound();
            finish();
        });

        int[] mShaderColors = new int[]{0xFFC3A6FF, 0xFFA158FF};
        mBinding.arcSeekBarEnergy.setProgressColor(mShaderColors);
        mBinding.arcSeekBarEnergy.setOnChangeListener(new ArcSeekBar.OnChangeListener() {

            @Override
            public void onStartTrackingTouch(boolean isCanDrag) {

            }

            @Override
            public void onProgressChanged(float progress, float max, boolean fromUser) {
                mViewModel.setEnergy((byte)(progress + energyOffset));
                mBinding.arcSeekBarEnergy.setLabelText(String.valueOf((byte)(progress + energyOffset)));
            }

            @Override
            public void onStopTrackingTouch(boolean isCanDrag) {
                playClickSound();
            }

            @Override
            public void onSingleTapUp() {

            }
        });

        mBinding.arcSeekBarIdhp.setProgressColor(mShaderColors);
        mBinding.arcSeekBarIdhp.setOnChangeListener(new ArcSeekBar.OnChangeListener() {
            @Override
            public void onStartTrackingTouch(boolean isCanDrag) {

            }

            @Override
            public void onProgressChanged(float progress, float max, boolean fromUser) {
                mViewModel.getIdhp().setValue((int) (progress + idhpOffset));
                mBinding.arcSeekBarIdhp.setLabelText(String.valueOf((int) (progress + idhpOffset)));
            }

            @Override
            public void onStopTrackingTouch(boolean isCanDrag) {
                playClickSound();
            }

            @Override
            public void onSingleTapUp() {

            }
        });
        mBinding.arcSeekBarIdhp.setProgress(0);

        mBinding.arcSeekBarIdlp.setProgressColor(mShaderColors);
        mBinding.arcSeekBarIdlp.setOnChangeListener(new ArcSeekBar.OnChangeListener() {
            @Override
            public void onStartTrackingTouch(boolean isCanDrag) {

            }

            @Override
            public void onProgressChanged(float progress, float max, boolean fromUser) {
                mViewModel.getIdlp().setValue((int) (progress + idlpOffset));
                mBinding.arcSeekBarIdlp.setLabelText(String.valueOf((int) (progress + idlpOffset)));
            }

            @Override
            public void onStopTrackingTouch(boolean isCanDrag) {
                playClickSound();
            }

            @Override
            public void onSingleTapUp() {

            }
        });
        mBinding.arcSeekBarIdlp.setProgress(0);

        mBinding.arcSeekBarIdp.setProgressColor(mShaderColors);
        mBinding.arcSeekBarIdp.setProgressColor(mShaderColors);
        mBinding.arcSeekBarIdp.setOnChangeListener(new ArcSeekBar.OnChangeListener() {
            @Override
            public void onStartTrackingTouch(boolean isCanDrag) {

            }

            @Override
            public void onProgressChanged(float progress, float max, boolean fromUser) {
                mViewModel.getIdp().setValue((int) (progress + idpOffset));
                mBinding.arcSeekBarIdp.setLabelText(String.valueOf((int) (progress + idpOffset)));
            }

            @Override
            public void onStopTrackingTouch(boolean isCanDrag) {
                playClickSound();
            }

            @Override
            public void onSingleTapUp() {

            }
        });
        mBinding.arcSeekBarIdp.setProgress(0);

        List<String> wheelLeftData = new ArrayList();
        wheelLeftData.add("- -");
        for (int i = 10; i <= 600; i++) {
            wheelLeftData.add(String.valueOf(i));
        }
        mBinding.handleRadioWheelContinuousDischargePeriod.setData(wheelLeftData);
        mBinding.handleRadioWheelContinuousDischargePeriod.setOnItemSelectedListener((picker, data, position) -> {
            playClickSound();
            mViewModel.getContinuousDischargePosition().setValue(position);
            mViewModel.getContinuousDischargePeriod().setValue(position == 0?0:Short.valueOf((String) data));
        });

        mBinding.handleRadioWheelRightDepth.setOnItemSelectedListener((picker, data, position)->{
            playClickSound();
            mViewModel.getDepthPosition().setValue(position);
            mViewModel.getDepth().setValue((byte)(Float.parseFloat((String)data) * 10));
        });

        mBinding.handleRadioWheelPressure.setOnItemSelectedListener((picker, data, position)->{
            playClickSound();
            mViewModel.getSkinPressurePosition().setValue(position);
            mViewModel.getSkinPressure().setValue(position == 0 ? 0: Integer.parseInt((String) data));
        });
    }

    @Override
    protected void loadData() {
//        mBinding.handleRadioInfo.setText(isTcpConnected()?"已连接":"未连接");

        mBinding.setViewModel(mViewModel);

        mViewModel.queryOperationParams(SPHelper.getCurrentUserInfo(this).getName());
    }

    @Override
    protected void observeData() {
        mViewModel.getOperationParamsList().observe(this, operationParamsList -> {
            if (operationParamsList != null) {
                mShortcutInfoAdapter.setData(operationParamsList);

                if(isInitialized){
                   return;
                }
                for (OperationParams operationParams : operationParamsList) {
                    if (operationParams.getPosition() == Const.POSITION_PREVIOUS_PARAMS && !operationParams.isEmpty()) {
                        Log.e("12121", "position为6 有参数 " + new Gson().toJson(operationParams));
                        isInitialized = true;
                        restoreDataAndParams(operationParams);
                        break;
                    }
                }
            }
        });


        mViewModel.getIsIntermittentMode().observe(this, isIntermittentMode -> {
//            当断续/连续模式的值发生改变时，先判断当前是否处于待机状态
            if (Boolean.TRUE.equals(mViewModel.getIsStandByState().getValue())){
                setArcSeekBarEnabled(mBinding.arcSeekBarIdp,isIntermittentMode,false);
                setArcSeekBarEnabled(mBinding.arcSeekBarIdlp,isIntermittentMode,false);
                setArcSeekBarEnabled(mBinding.arcSeekBarIdhp,isIntermittentMode,false);
                setWheelPickerEnabled(mBinding.handleRadioWheelContinuousDischargePeriod,!isIntermittentMode);
            }
        });

        mViewModel.getFrequency().observe(this, freq -> {
            if (freq == 1) {
                energyOffset = 5;
                if (getMachineType(this).equals(Const.MACHINE_TYPE_TAISHI)) {
                    mBinding.arcSeekBarEnergy.setMax(25);
                } else {
                    mBinding.arcSeekBarEnergy.setMax(45);
                }
                if (mViewModel.getEnergy() < 5){
                    mBinding.arcSeekBarEnergy.setProgress(5 - energyOffset + 2);
                }else {
                    mBinding.arcSeekBarEnergy.setProgress(mViewModel.getEnergy() - energyOffset);
                }
            }else {
                energyOffset = 3;
                if (getMachineType(this).equals(Const.MACHINE_TYPE_TAISHI)) {
                    mBinding.arcSeekBarEnergy.setMax(12);
                    if (mViewModel.getEnergy() > 15) {
                        mBinding.arcSeekBarEnergy.setProgress(12);
                    }else {
                        mBinding.arcSeekBarEnergy.setProgress(mViewModel.getEnergy() - energyOffset);
                    }
                } else {
                    mBinding.arcSeekBarEnergy.setMax(17);
                    if (mViewModel.getEnergy() > 20){
                        mBinding.arcSeekBarEnergy.setProgress(17);
                    }else {
                        mBinding.arcSeekBarEnergy.setProgress(mViewModel.getEnergy() - energyOffset);
                    }
                }
            }
        });
        mViewModel.getIsStandByState().observe(this, isStandByState -> {
            mViewModel.saveDataToFile("p:isStandByState changed:"+isStandByState);
            mBinding.handleRadioStart.setText(isStandByState?"待机":"准备");
            setArcSeekBarEnabled(mBinding.arcSeekBarEnergy,isStandByState,true);

            if (isStandByState) {
                setArcSeekBarEnabled(mBinding.arcSeekBarIdp,mViewModel.getIsIntermittentMode().getValue(),false);
                setArcSeekBarEnabled(mBinding.arcSeekBarIdlp,mViewModel.getIsIntermittentMode().getValue(),false);
                setArcSeekBarEnabled(mBinding.arcSeekBarIdhp,mViewModel.getIsIntermittentMode().getValue(),false);
                setWheelPickerEnabled(mBinding.handleRadioWheelContinuousDischargePeriod,!mViewModel.getIsIntermittentMode().getValue());
                mViewModel.resetState();
            }else {
                setArcSeekBarEnabled(mBinding.arcSeekBarIdhp, false,false);
                setArcSeekBarEnabled(mBinding.arcSeekBarIdlp, false,false);
                setArcSeekBarEnabled(mBinding.arcSeekBarIdp, false,false);
                setWheelPickerEnabled(mBinding.handleRadioWheelContinuousDischargePeriod,false);

                //          点击开始后，保存当前的参数，位置为6，与预置参数的0-5进行区分
                mViewModel.saveQuickOperationParam(SPHelper.getCurrentUserInfo(this),Const.POSITION_PREVIOUS_PARAMS);
                waitEnergyBoardReply = true;
                mViewModel.sendPreCommand();
                if (readyToPlaySound7 && isElectrodeDetected){
                    playExceptionSound(7);
                    readyToPlaySound7 = false;
                }

            }

            setWheelPickerEnabled(mBinding.handleRadioWheelPressure,isStandByState);
            setWheelPickerEnabled(mBinding.handleRadioWheelRightDepth,isStandByState);
            mShortcutInfoAdapter.setIsStandBy(isStandByState);
        });

        mViewModel.getIsWorkingState().observe(this, isWorkingState -> {
            if (!mViewModel.getIsStandByState().getValue()) {
                mBinding.handleRadioStart.setText(isWorkingState?"工作":"准备");
            }
        });

        mViewModel.getToastInfo().observe(this, toastInfo -> {
            Log.e("12121","getToastInfo........."+toastInfo);
            Toast.makeText(this,toastInfo,Toast.LENGTH_SHORT).show();
        });
    }

    private void setArcSeekBarEnabled(ArcSeekBar arcSeekBar,boolean enabled,boolean isBig){
        arcSeekBar.setEnabledDrag(enabled);
        arcSeekBar.setEnabledSingle(enabled);
        if (enabled) {
            int[] mShaderColors = new int[]{0xff5d7dff, 0xffa158ff};
            arcSeekBar.setProgressColor(mShaderColors);
            if (isBig) arcSeekBar.setThumbDrawable(R.mipmap.icon_thumb_big);
            else arcSeekBar.setThumbDrawable(R.mipmap.icon_thumb);
        } else {
            arcSeekBar.setProgressColor(getResources().getColor(R.color.purple_dark1));
            arcSeekBar.setThumbDrawable(R.mipmap.icon_thumb_gray);
        }
        arcSeekBar.setLabelTextColor(enabled? getResources().getColor(R.color.purple) : getResources().getColor(R.color.gray_8b8b8a));
    }

    private void setWheelPickerEnabled(WheelPicker wheelPicker, boolean enabled){
        wheelPicker.setEnabled(enabled);
        wheelPicker.setBackground(enabled? getResources().getDrawable(R.mipmap.bg_wheel_enabled) : getResources().getDrawable(R.mipmap.bg_wheel_disabled));
        wheelPicker.setSelectedItemTextColor(enabled? getResources().getColor(R.color.purple) : getResources().getColor(R.color.gray_8b8b8a));
        wheelPicker.setItemTextColor(enabled? getResources().getColor(R.color.white) : getResources().getColor(R.color.gray_8b8b8a));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void OnEvent(MessageEvent messageEvent){
        if (messageEvent.getCode() == Const.ADDRESS_FROM_HANDLE_1_DATA_1) {
            Bean1FromHandle bean1FromHandle = (Bean1FromHandle) messageEvent.getData();
            byte workState = bean1FromHandle.getWorkState();
            boolean isWorking = (workState & (byte) 0x01) == 1;
            if (isWorking) {
                mViewModel.saveDataToFile("p:handle working data "+new Gson().toJson(bean1FromHandle));
            }
            isHandleWorking = isWorking;
//            Log.e("12121","work state:"+isWorking);
            mBinding.handleImg.setSelected(isWorking);

            if (Boolean.FALSE.equals(mViewModel.getIsWorkingState().getValue())) {
                if (isWorking) {
                    mViewModel.sendHandleCommand();
                }
            }else {
                if (!isWorking) {
                    mViewModel.sendHandleCommand();
                }
            }
//            if (!isWorking && isHandleWorking) {
//                if (Boolean.FALSE.equals(mViewModel.getIsStandByState().getValue())) {
//                    mViewModel.getIsStandByState().setValue(true);
//                }
//                if (Boolean.TRUE.equals(mViewModel.getIsWorkingState().getValue())){
//                    mViewModel.getIsWorkingState().setValue(false);
//                }
//            }
//            isHandleWorking = isWorking;

            if ((workState >> 4 & (byte)0x01) == 0) {
                isElectrodeDetected = false;
                showErrMsg("未识别治疗电极 ");
                readyToPlaySound7 = true;
                mBinding.handleRadioElectrodeCount.setVisibility(View.GONE);
                mBinding.npReplaceElectrode.setVisibility(View.VISIBLE);
                AnimUtils.startBlink(mBinding.npReplaceElectrode);
                if (Boolean.FALSE.equals(mViewModel.getIsStandByState().getValue())) {
                    mViewModel.getIsStandByState().setValue(true);
                    mViewModel.getIsWorkingState().setValue(false);
                }
                return;
            } else {
                isElectrodeDetected = true;
                mViewModel.getInfo().setValue("");
                mBinding.handleRadioElectrodeCount.setVisibility(View.VISIBLE);
                mBinding.npReplaceElectrode.setVisibility(View.GONE);
                if (bean1FromHandle.getElectrode_count()[0] == 0) {
                    mBinding.handleRadioElectrodeCount.setText("- - -");
                }else {
                    String name = ByteUtil.convertByteArrayToASCIIString(bean1FromHandle.getElectrode_count());
                    if (name.contains("B")) {
                        mBinding.handleRadioElectrodeCount.setText(name);
                    }else {
                        mBinding.handleRadioElectrodeCount.setText(name.substring(1));
                    }

                }
            }

            byte exception = bean1FromHandle.getException();
            isBit6HasException = (exception >> 6 & 1) == 1;
//            Log.e("12121","exception:"+exception+";isBit6HasException:"+ isBit6HasException +";isPreviousBit6HasException:"+isPreviousBit6HasException);
            if (isBit6HasException) {
                if (!isPreviousBit6HasException) {
//                    如果上一次没有故障，本次出现，则报故障 语音
                    playExceptionSound(6);
                }
            }
            isPreviousBit6HasException = isBit6HasException;
            if (isBit6HasException) {
//                mViewModel.saveDataToFile("p:handle exception E600");
                showErrMsg("E600");
                return;
            }
//退针卡滞故障
            boolean isBit7HasException = (exception >> 7 & 1) == 1;
//            Log.e("12121","exception:"+exception+";isBit7HasException:"+isBit7HasException+";isPreviousBit7HasException:"+isPreviousBit7HasException);
            if (isBit7HasException) {
                if (!isPreviousBit7HasException) {
                    playExceptionSound(7);
                    new AlertDialog.Builder(this)
                            .setMessage("请拔掉治疗电极头固定销")
                            .setPositiveButton("确定", (dialog, which) -> {
                                try {
                                    // 确定按钮点击事件 清除故障位
                                    sendMessage(CommandGenerator.commandToEraseException(Const.ADDRESS_TO_HANDLE_1_DATA_1));
                                } catch (StructException e) {
                                    throw new RuntimeException(e);
                                }
                            })
                            .show();
                }
            }
            isPreviousBit7HasException = isBit7HasException;

            StringBuilder errInfo = new StringBuilder();
//            非待机状态下才给是否吸附的提示信息
            if (!mViewModel.getIsStandByState().getValue()) {
                if ((exception >> 2 & 0x01) == 1) {
                    errInfo.append("未吸附:").append(bean1FromHandle.getPressure()).append(" ");
                }
            }
            if ((exception >> 1 & 0x01) == 1){
                errInfo.append("E601 ");
            }
            if ((exception & 1) == 1 ) {
                errInfo.append("治疗电极次数用完 ");
            }
            if (!errInfo.toString().isEmpty()){
                showErrMsg(errInfo.toString());
            }

            if (bean1FromHandle.getSkinResistance() != -1) {
                mBinding.skinResistance.setText(bean1FromHandle.getSkinResistance()+"");
            }

            int unsignedTotalPower = ((int) bean1FromHandle.getTotalPower()) & 0xFFFF; // 转为无符号 int
            if (Boolean.TRUE.equals(mViewModel.getIsMJ().getValue())) {
                mBinding.totalPower.setText(String.valueOf(unsignedTotalPower));
                mBinding.outputEnergyTitle.setText("输出能量mJ");
            } else {
                mBinding.totalPower.setText(String.format("%.2f", unsignedTotalPower / 1000.0f));
                mBinding.outputEnergyTitle.setText("输出能量J");
            }
            mViewModel.getShengyucishu().setValue(bean1FromHandle.getShengyucishu());
        } else if (messageEvent.getCode() == Const.ADDRESS_FROM_BOTTOM_BOARD){
            if (!mViewModel.getIsStandByState().getValue()) {
                BeanFromBottomBoard beanFromBottomBoard = (BeanFromBottomBoard) messageEvent.getData();
                mViewModel.saveDataToFile("p:bottom board working data " + new Gson().toJson(beanFromBottomBoard));
                int devStatus = beanFromBottomBoard.getDev_status();
                int bitMask = 1 << 1;
                if ((bitMask & devStatus) == 2) {//脚踏开关输入，
                    if (isAccept) {
                        isAccept = false;
//                        接收到脚踏信号后，判断电极是否有，如果有，则正常工作，如果没有，语音提示
                        if (isElectrodeDetected) {
//                            如果当前深度大于2，但是压力小于45，则播放压力过低提示
//                       否则  如果当前深度大于1，但是压力小于40，则播放压力过低提示
                            if (!mViewModel.getIsWorkingState().getValue()) {
                                if (mViewModel.getDepth().getValue() >= 20 && mViewModel.getSkinPressure().getValue() != 0){
                                    if (Math.abs(mViewModel.getCorrectedPressure()) < 4500){
                                        playSound("pressure_low");
                                    }
                                }else if (mViewModel.getDepth().getValue() >= 10 && mViewModel.getSkinPressure().getValue() != 0){
                                    if (Math.abs(mViewModel.getCorrectedPressure()) < 4000){
                                        playSound("pressure_low");
                                    }
                                }
                            }
                            mViewModel.saveDataToFile("p:Foot switch pressed");
                            mViewModel.getIsWorkingState().setValue(!mViewModel.getIsWorkingState().getValue());
                            mViewModel.sendHandleCommand();
                        }else {
                            playInstallElectrodeSound();
                        }
                    }
                }else {//0脚踏开关释放
                    isAccept = true;
                }
            }
        } else if (messageEvent.getCode() == Const.TCP_CONNECT_STATUS) {
//            boolean isConnect = (Boolean) messageEvent.getData();
//            mBinding.handleRadioInfo.setText(isConnect ? "已连接" : "未连接");
        } else if (messageEvent.getCode() == Const.EVENTBUS_HANDLE_STATE) {
            DeviceStatus handleState = (DeviceStatus) messageEvent.getData();
            if (!handleState.isPressureHandleOnline()) {
                mViewModel.saveDataToFile("p:handle disconnect");
                mViewModel.resetState();
                finish();
            }
        } else if (messageEvent.getCode() == Const.ADDRESS_FROM_ENERGY_BOARD) {
            if (Boolean.TRUE.equals(mViewModel.getIsWorkingState().getValue())) {
                BeanFromEnergyBoard beanFromEnergyBoard = (BeanFromEnergyBoard) messageEvent.getData();
                mViewModel.saveDataToFile("p:energy board working data " + new Gson().toJson(beanFromEnergyBoard));
            }
        } else if (messageEvent.getCode() == Const.ADDRESS_FROM_NEGATIVE_PRESSURE_BOARD) {
            if (Boolean.TRUE.equals(mViewModel.getIsWorkingState().getValue())) {
                BeanFromNegativePressureBoard beanFromNegativePressureBoard = (BeanFromNegativePressureBoard) messageEvent.getData();
                mViewModel.saveDataToFile("p:negative pressure board working data " + new Gson().toJson(beanFromNegativePressureBoard));
            }

        }
    }

    final static int COUNTS = 5;// 点击次数
    final static long DURATION = 1000;// 规定有效时间
    long[] mHits = new long[COUNTS];
    private void continuousClick() {
        //每次点击时，数组向前移动一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        //为数组最后一位赋值
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION)) {
            mHits = new long[COUNTS];//重新初始化数组
            startActivity(new Intent(this, EngineerActivity.class));
        }
    }

    class ShortcutInfoAdapter extends RecyclerView.Adapter<ShortcutInfoAdapter.InnerViewHolder>{

        List<OperationParams> mOperationParams = new ArrayList<>();
        boolean isStandBy = true;

        @NonNull
        @Override
        public HandleRadioActivity.ShortcutInfoAdapter.InnerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            ItemShortcutInfoBinding mBinding = ItemShortcutInfoBinding.inflate(getLayoutInflater());
            return new ShortcutInfoAdapter.InnerViewHolder(mBinding);
        }

        @Override
        public void onBindViewHolder(@NonNull InnerViewHolder holder, int position) {
            if (mOperationParams.isEmpty()) {
                return;
            }
            holder.mItemView.getRoot().setEnabled(isStandBy);
            OperationParams operationParam = mOperationParams.get(position);
//            holder.mItemView.itemShortcutInfoName.setText(operationParam.getPosition()+"");
            if (operationParam.isEmpty()) {
                holder.mItemView.itemShortcutInfoName.setBackgroundResource(mShortcutList.get(position));
            }else {
                holder.mItemView.itemShortcutInfoName.setBackgroundResource(mShortcutLList.get(position));
            }

            holder.mItemView.getRoot().setOnClickListener(v -> {
                playClickSound();
                if (Boolean.TRUE.equals(mViewModel.getIsPreMode().getValue())) {
                    mViewModel.saveQuickOperationParam(SPHelper.getCurrentUserInfo(getBaseContext()),position+1);
                    Toast.makeText(getBaseContext(), "保存成功!", Toast.LENGTH_SHORT).show();
                }else {
                    if (!operationParam.isEmpty()) {
                        restoreDataAndParams(operationParam);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return 5;
        }

        class InnerViewHolder extends RecyclerView.ViewHolder{

            private final ItemShortcutInfoBinding mItemView;

            public InnerViewHolder(@NonNull ItemShortcutInfoBinding itemView) {
                super(itemView.getRoot());
                mItemView = itemView;
            }
        }

        @SuppressLint("NotifyDataSetChanged")
        public void setData(List<OperationParams> shortcutInfo){
            mOperationParams.clear();
            mOperationParams.addAll(shortcutInfo);
            notifyDataSetChanged();
        }

        @SuppressLint("NotifyDataSetChanged")
        public void setIsStandBy(boolean isStandBy){
            this.isStandBy = isStandBy;
            notifyDataSetChanged();
        }
    }

    private void restoreDataAndParams(OperationParams operationParam){
//        恢复脉冲/连续相关状态
        mViewModel.getIsIntermittentMode().setValue(operationParam.isIntermittentMode());
        if (operationParam.isIntermittentMode()) {
            mBinding.arcSeekBarIdp.setProgress(operationParam.getIntermittentDischargePulse() - idpOffset);
            mBinding.arcSeekBarIdlp.setProgress(operationParam.getIntermittentDischargeLowLevelPeriod() - idlpOffset);
            mBinding.arcSeekBarIdhp.setProgress(operationParam.getIntermittentDischargeHighLevelPeriod() - idhpOffset);
        }else {
            mViewModel.getContinuousDischargePeriod().setValue(operationParam.getContinuousDischargePeriod());
            mViewModel.getContinuousDischargePosition().setValue(operationParam.getContinuousDischargePosition());
            mBinding.handleRadioWheelContinuousDischargePeriod.setSelectedItemPosition(operationParam.getContinuousDischargePosition());
        }

//                  恢复频率相关状态
        mViewModel.getFrequency().setValue(operationParam.getFreq());
        mBinding.arcSeekBarEnergy.setProgress(operationParam.getPower() - energyOffset);

//                    恢复皮肤负压相关状态
        mViewModel.getSkinPressure().setValue((int) operationParam.getPressure());
        mViewModel.getSkinPressurePosition().setValue(operationParam.getPressurePosition());
        mBinding.handleRadioWheelPressure.setSelectedItemPosition(operationParam.getPressurePosition());

//                     恢复刺入深度
        mViewModel.getDepth().setValue(operationParam.getDepth());
        mViewModel.getDepthPosition().setValue(operationParam.getDepthPosition());
        mBinding.handleRadioWheelRightDepth.setSelectedItemPosition(operationParam.getDepthPosition());
    }

    private void showErrMsg(String errInfo){
        mViewModel.getInfo().setValue(errInfo);
        if (!errInfo.isEmpty()) {
            AnimUtils.startBlink(mBinding.handleRadioInfo);
        }
    }

}